package com.xugongzhang.thread;

import com.xugongzhang.dto.Message;
import com.xugongzhang.enums.MessageTypeEnum;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.util.Arrays;

/**
 * @author X
 * @date 2022/11/26 17:09
 */
@Data
@NoArgsConstructor
public class ClientConnectServerThread extends Thread {
    
   private Socket socket;

    @Override
    public void run() {
        // 线程需要和服务器一直通信，所以一直循环
        while (true) {
            System.out.println("客户端线程等待接收服务器消息");
            try {
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                // 如果接收不到服务器的消息，程序会阻塞在此
                Message message = (Message) ois.readObject();
                // 根据messageType区分业务，做不同的处理
                if (message.getMsgType().equals(MessageTypeEnum.RET_ONLINE_FRIEND.getMessageType())) {
                    String[] userList = message.getContent().split(" ");
                    System.out.println("\n =====在线用户列表=====");
                    Arrays.stream(userList).forEach(item -> System.out.println("用户：" + item));
                }
                else if (message.getMsgType().equals(MessageTypeEnum.COMM_MSG.getMessageType())) {
                    String info = message.getContent();
                    System.out.println(message.getSendTime() + "\t" + message.getSender() + "对我说：" + info);
                }
                else if (message.getMsgType().equals(MessageTypeEnum.TO_ALL_MSG.getMessageType())) {
                    String toAllInfo = message.getContent();
                    System.out.println(message.getSendTime() + "\t" + message.getSender() + "对大家说：" + toAllInfo);
                }
                else if (message.getMsgType().equals(MessageTypeEnum.FILE_MSG.getMessageType())) {
                    System.out.println("\n" + message.getSender() + " 给 " + message.getGetter()
                                            + " 发送了文件到我的电脑：" + message.getDest());
                    // 文件输出流，把文件写到我的磁盘
                    FileOutputStream fileOutputStream = new FileOutputStream(message.getDest());
                    fileOutputStream.write(message.getFileBytes());
                    fileOutputStream.close();
                    System.out.println("保存成功！");
                }
                else {
                    System.out.println("other...");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public ClientConnectServerThread(Socket socket) {
        this.socket = socket;
    }
}
